<?php
/**
 * Created by PhpStorm.
 * User: deng
 * Date: 2015/3/29
 * Time: 16:17
 */

namespace Common\Controller;

use Think\Controller\RestController;

/**
 * Class ApiController
 * @package Common\Controller
 * 总体的api类，需要提供一些基础的初始化、以及一些常用的方法
 */
class ApiController extends RestController
{

    protected $_request;

    public function __construct()
    {
        $this->allowMethod = ['get', 'post', 'put', 'delete', 'options', 'head'];
        parent::__construct();
        /*
         * Cors head config
         */
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Headers: If-Modified-Since, Origin,Keep-Alive,Accept, Content-Type, X-Token");
        header("Access-Control-Max-Age: 60");
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        $this->request();
    }

    public function options($header = 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE')
    {
        if (empty($header))
            Success(200);
        if (is_array($header)) {
            foreach ($header as $key => $value) {
                header($value);
            }
        } else {
            header($header);
        }
        Success(200);
    }

    protected function request()
    {
        //对前台的参数data处理
        if ($this->_method == 'get') {
            $this->_request = $_GET;
        } else {
            $request = get_object_vars(json_decode(file_get_contents('php://input')));
            $this->_request = $this->object_to_array($request);
        }
    }

    protected function object_to_array($obj)
    {
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        foreach ($_arr as $key => $val) {
            $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val;
            $arr[$key] = $val;
        }
        return $arr;
    }
}